package cmd

import (
	"context"
	"fmt"
	"log"
	"os"
	"os/exec"
	"strconv"
	"time"

	"system-admin/config"
	"system-admin/config/redis"
	"system-admin/internal/app/grpc"
	"system-admin/internal/app/web/crond"
	"system-admin/internal/app/web/middleware"
	"system-admin/internal/app/web/routers"
	"system-admin/internal/define"
	"system-admin/internal/migrate"

	"192.168.1.75/go-pkg/logx/propagation/extract"
	"github.com/fvbock/endless"
	"github.com/gin-gonic/gin"
	"github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
	Use:   "hugo",
	Short: "Hugo is a very fast static site generator",
	Long: `A Fast and Flexible Static Site Generator built with
                love by spf13 and friends in Go.
                Complete documentation is available at http://hugo.spf13.com`,
	// 当没有命令参数时，自动执行的函数
	// 否则不会执行下面的函数
	Run: func(cmd *cobra.Command, args []string) {
		// 定时任务初始化
		crond.CrondInit()
		// 数据库检查更新
		migrate.AutoMigrate()
		// 缓存应用的版本
		ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
		defer cancel()
		rdb := redis.NewDB()
		rdb.Set(ctx, define.RedisAppVersion, define.APPVersion, 0).Result()
		// 监听重启信号,并进行重启
		grpcCtx, grpcCancel := context.WithCancel(context.Background())
		defer grpcCancel()
		{
			tk := time.NewTicker(time.Second)
			defer tk.Stop()
			if !config.Config.DisableRestartCheck {
				go func() {
					for {
						<-tk.C
						// 读取数据库应用的版本,发现版本不一致，执行重启
						if ver, err := redis.NewDB().Get(context.Background(), define.RedisAppVersion).Result(); err == nil {
							if ver != define.APPVersion {
								grpcCancel()
								time.Sleep(time.Second)
								cmd := exec.Command("kill", "-1", strconv.Itoa(os.Getpid()))
								cmd.Run()
							}
						}
					}
				}()
			}
		}
		// 启动grpc
		go func() {
			grpc.StartGrpc(grpcCtx, config.Config.GRPCPort)
		}()
		// 启动http
		{
			router := gin.Default()
			// 注册中间件
			router.Use(
				extract.GinMiddleware("system-admin"), // 获取B3
				middleware.InjectTraceID(),            // 注入链路追踪trace_id
				middleware.HealthCheck(),              // 健康检查响应
				middleware.ParamsHandle(),             // 参数预处理
				middleware.Cors(),                     // 跨域
				middleware.Auth(),                     // 权限认证，登录认证及接口认证
				middleware.Proxy(),                    // 根据服务名称，进行服务反向代理
			)
			// 注册路由
			routers.Default(router)
			// 启动http服务
			endless.DefaultHammerTime = time.Second * 5
			endless.ListenAndServe(":"+config.Config.HTTPPort, router)
		}
		log.Println("system-admin restart")
		os.Exit(0)
	},
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
